<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreOrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'address_id' => 'required|exists:user_addresses,id',
            'notes' => 'nullable|string|max:500',
            'user_coupon_id' => 'nullable|exists:user_coupons,id',
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'address_id.required' => '请选择收货地址',
            'address_id.exists' => '收货地址不存在',
            'notes.max' => '订单备注不能超过500个字符',
            'user_coupon_id.exists' => '优惠券不存在',
        ];
    }

    /**
     * Configure the validator instance.
     */
    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            // 验证地址是否属于当前用户
            if ($this->address_id) {
                $address = \App\Models\UserAddress::find($this->address_id);
                if ($address && $address->user_id !== auth()->id()) {
                    $validator->errors()->add('address_id', '无权使用此地址');
                }
            }
        });
    }
}